﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;

namespace com.sharepointutils.app.Controls
{
    /// <summary>
    /// Interaction logic for XmlViewer.xaml
    /// </summary>
    public partial class XmlViewer : UserControl
    {
        private XmlDocument _xmldocument;

        public XmlViewer()
        {
            InitializeComponent();
        }




        public String Text
        {
            get { return (String)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Text.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register("Text", typeof(String), typeof(XmlViewer), new PropertyMetadata(null, TextChanged));

        private static void TextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            XmlViewer viewer = d as XmlViewer;
            if (d != null)
            {
                XmlDocument document = new XmlDocument();
                document.LoadXml(e.NewValue as String);
                d.SetCurrentValue(XmlDocumentProperty, document);
            }

        }

        public XmlDocument XmlDocument
        {
            get { return (XmlDocument)GetValue(XmlDocumentProperty); }
            set { SetValue(XmlDocumentProperty, value); }
        }

        // Using a DependencyProperty as the backing store for XmlDocument.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty XmlDocumentProperty =
            DependencyProperty.Register("XmlDocument", typeof(XmlDocument), typeof(XmlViewer), new PropertyMetadata(null, XmlDocumentChanged));


        private static void XmlDocumentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {

            XmlViewer viewer = d as XmlViewer;
            if (d != null)
            {
                if (e.NewValue == null)
                {
                    viewer.xmlTree.ItemsSource = null;
                    return;
                }

                XmlDataProvider provider = new XmlDataProvider();
                provider.Document = e.NewValue as XmlDocument;
                Binding binding = new Binding();
                binding.Source = provider;
                binding.XPath = "child::node()";
                viewer.xmlTree.SetBinding(TreeView.ItemsSourceProperty, binding);


            }

        }
    }
}
